﻿using System;
using System.Web;
using System.Web.Mvc;

namespace LdCms.Web.Framework
{
    using LdCms.IBLL.Log;
    using LdCms.Common.Logs;
    using LdCms.EF.DbModels;

    public class ExceptionHandlerAttribute : ActionFilterAttribute, IExceptionFilter
    {
        private IErrorRecordService ErrorRecordService { get; set; }
        /// <summary>
        /// 异常
        /// </summary>
        /// <param name="filterContext"></param>
        public void OnException(ExceptionContext filterContext)
        {
            try
            {
                //获取异常信息，入库保存
                Exception error = filterContext.Exception;
                string message = error.Message;                          //错误信息描述
                string url = HttpContext.Current.Request.RawUrl;         //错误发生地址
                string ipAddress = HttpContext.Current.Request.UserHostAddress; //获取用户IP地址

                //bool result = SaveErrorRecord(url, message, ipAddress);

                LogsManager.LogPath = string.Empty;
                LogsManager.WriteLog(LogsFile.Error, string.Format("--全局异常过滤器捕获的异常--开始------------"));
                LogsManager.WriteLog(LogsFile.Error, string.Format("系统编号：{0}", BaseSystemConfig.SystemID));
                LogsManager.WriteLog(LogsFile.Error, string.Format("访问网址：{0}", url));
                LogsManager.WriteLog(LogsFile.Error, string.Format("异常信息：{0}", message));
                LogsManager.WriteLog(LogsFile.Error, string.Format("IP地址：{0}", ipAddress));
               // LogsManager.WriteLog(LogsFile.Error, string.Format("保存结果：{0}", result));
                LogsManager.WriteLog(LogsFile.Error, string.Format("--全局异常过滤器捕获的异常--结束------------"));

            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        private bool SaveErrorRecord(string url, string message, string ipAddress)
        {
            try
            {
                return ErrorRecordService.SaveErrorRecord(new Ld_Log_ErrorRecord()
                {
                    SystemID = BaseSystemConfig.SystemID,
                    Url = url,
                    Message = message,
                    IpAddress = ipAddress,
                    State = true
                });
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
    }
}